<template>
  <!--  <form-create :rule="rule" v-model:api="fApi" :option="options"/>-->
  <div>
    <form-create
      style="margin-left: -5px"
      :rule="ruleData"
      v-model="fApi"
      :option="options"
      :value.sync="formData"
    />
    <div class="toolbar">
      <el-button type="primary" size="mini" @click="updateLayerData">保存</el-button>
      <el-button plain size="mini" @click="reset">重置</el-button>
    </div>
    <el-image-viewer
      v-if="imagePreview.show"
      :on-close="
        () => {
          imagePreview.show = false;
        }
      "
      :initial-index="imagePreview.index"
      :url-list="imagePreview.imageList"
    />
  </div>
</template>

<script>
import PiplineProjectController from '../../../api/Controller/PiplineProjectController';
import { getToken, getAppId } from '@/utils';
import { mapGetters } from 'vuex';
import { EventBus } from '@/utils/bus';
// 表单标签显示的最大字数（超出7个字数时，显示为省略号）
const MAX_LABEL_WORDS = 5;

export default {
  name: 'EditWindow',
  props: {
    projectId: {
      type: String
    },
    layerId: {
      type: String
    },
    dataId: {
      type: String
    },
    supportImage: {
      type: Boolean,
      default: false
    },
    imageNumbers: {
      type: Number,
      default: 3
    },
    fieldList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    layerConfig: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      isEditTask: true,
      fApi: {},
      ruleData: [],
      imagePreview: {
        show: false,
        index: 0,
        imageList: []
      },
      options: {
        form: {
          size: 'mini',
          labelPosition: 'right', //是否显示校验错误信息
          showMessage: true,
          inlineMessage: false,
          labelWidth: '92px'
        },
        // onSubmit: formData => {
        //   alert(JSON.stringify(formData));
        //   this.updateLayerData(formData)
        // },
        submitBtn: false,
        resetBtn: false
      },
      formData: {}
    };
  },
  components: {
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  methods: {
    onCancel(isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    },
    reset() {
      this.fApi.resetFields();
      this.loadData(true);
    },
    updateLayerData() {
      this.fApi.validate((valid, fail) => {
        if (valid) {
          let params = {
            projectId: this.projectId,
            layerId: this.layerId,
            dataId: this.dataId,
            data: this.formData
          };
          console.log('params', params);
          if (this.formData.nexImage) {
            params.data.relate_images = this.formData.nexImage.map(item => {
              return item.replace(window.config.baseUrl, '');
            });
          }

          // if (this.formData.farImage) {
          //   params.data.farImage = params.data.farImage.replace(window.config.baseUrl, '');
          // }
          // if (this.formData.nearImage) {
          //   params.data.nearImage = params.data.nearImage.replace(window.config.baseUrl, '');
          // }
          // if (this.formData.innerImage) {
          //   params.data.innerImage = params.data.innerImage.replace(window.config.baseUrl, '');
          // }
          PiplineProjectController.updateLayerData(this, params)
            .then(res => {
              console.log('更新成功');
              this.$message.success('更新成功');
              if (res.data && res.data.updatePipelineLayerData) {
                let updatedData = [...res.data.updatePipelineLayerData];
                EventBus.$emit('changeLineStyle', { dataList: updatedData });
              }
              if (res.data && res.data.updatePipepointLayerData) {
                let updatedData = [...res.data.updatePipepointLayerData];
                EventBus.$emit('changePointStyle', { dataList: updatedData });
              }
              this.onCancel(true);
            })
            .catch(err => {
              console.error('更新失败：', err);
              this.$message.error('更新失败');
            });
        } else {
          //todo 表单验证未通过
        }
      });
    },
    // 获取字段的规则
    getRuleData() {
      let maxLabelWords = 0;
      this.ruleData = [];
      console.log(this.fieldList, 'this.fieldList');
      this.fieldList.forEach(item => {
        if (item.isEditField === 1) {
          const ruleObject = this.buildRuleObject(item);
          if (ruleObject) {
            this.ruleData.push(ruleObject);
            if (ruleObject.title && ruleObject.title.length > maxLabelWords) {
              maxLabelWords = ruleObject.title.length;
            }
          }
        }
      });

      if (this.supportImage) {
        this.ruleData.push(this.buildUploadPicRule('远景照片', 'farImage'));
        this.ruleData.push(this.buildUploadPicRule('近景照片', 'nearImage'));
        this.ruleData.push(this.buildUploadPicRule('井内照片', 'innerImage'));
      }

      if (maxLabelWords > 0) {
        maxLabelWords = maxLabelWords > MAX_LABEL_WORDS ? MAX_LABEL_WORDS : maxLabelWords;
        this.options.form.labelWidth = maxLabelWords + 4 + 'rem';
        console.log(this.options.form.labelWidth);
      }
      this.loadData();
      //
      // if (!this.isEditTask) {
      //   this.ruleData.forEach(item => {
      //     item.props.disabled = true
      //   })
      // }
      console.log('ruleData', this.ruleData);
    },

    buildRuleObject(item) {
      let labelWords = item.displayName ? item.displayName.length : 0;

      let ruleObject = {
        props: {},
        col: { span: 24 },
        title:
          labelWords <= MAX_LABEL_WORDS
            ? item.displayName
            : {
                style: {
                  '--full-text': "'" + item.displayName + "'"
                },
                class: 'overlength-label',
                title: item.displayName,
                wrap: {
                  label: 'labelWords'
                }
              },
        field: item.name
      };

      const inputType = item.displayRule.inputType;

      switch (inputType) {
        case 'label':
          return this.buildLabelRule(item, ruleObject);
        case 'text':
        case 'textarea':
          return this.buildInputRule(item, ruleObject);
        case 'input':
          return this.buildInputNumberOrInputRule(item, ruleObject);
        case 'select_single':
          return this.buildSelectSingleRule(item, ruleObject);
        case 'select_multiple':
          return this.buildSelectMultipleRule(item, ruleObject);
        // case 'upload_pic':
        //   return this.buildUploadPicRule(item, ruleObject);
        // case 'upload_file':
        //   return this.buildUploadFileRule(item, ruleObject);
        case 'cascader':
          return this.buildCascaderRule(item, ruleObject);
        case 'datePicker':
          return this.buildDatePickerRule(item, ruleObject);
        default:
          console.log('未支持的字段类型：', inputType, '字段为：', item.name);
          return this.buildInputRule(item, ruleObject);
        // return ruleObject;
      }
    },

    // 添加 label 类型的构建方法
    buildLabelRule(item, ruleObject) {
      ruleObject.type = 'input';
      ruleObject.className = 'readonly_text';
      ruleObject.props = {
        type: 'text',
        readonly: true
      };
      return ruleObject;
    },
    buildInputRule(item, ruleObject) {
      ruleObject.type = 'input';
      ruleObject.props = {
        type: 'text',
        placeholder: '请输入' + item.displayName
      };
      ruleObject.validate = this.buildValidationRules(item);
      console.log('ruleObject', ruleObject);
      return ruleObject;
    },

    buildInputNumberOrInputRule(item, ruleObject) {
      const hasNumberRule =
        item.displayRule.validateRule &&
        item.displayRule.validateRule.length > 0 &&
        (item.displayRule.validateRule.indexOf('integer') !== -1 ||
          item.displayRule.validateRule.indexOf('number') !== -1);

      if (hasNumberRule) {
        return this.buildInputNumberRule(item, ruleObject);
      } else {
        return this.buildInputTextRule(item, ruleObject);
      }
    },

    buildInputNumberRule(item, ruleObject) {
      ruleObject.type = 'inputNumber';
      ruleObject.props = {
        disabled: false,
        placeholder: '请输入' + item.displayName
      };
      ruleObject.validate = [];

      if (item.displayRule.isRequired === 1) {
        ruleObject.validate.push({
          required: true,
          message: '请输入' + item.displayName
        });
      }

      if (item.displayRule.validateRule && item.displayRule.validateRule.length > 0) {
        item.displayRule.validateRule.forEach(rule => {
          if (rule === 'min') {
            ruleObject.props.min = Number(item.displayRule.validateMinValue);
          } else if (rule === 'max') {
            ruleObject.props.max = Number(item.displayRule.validateMaxValue);
          }
        });
      }
      return ruleObject;
    },

    buildInputTextRule(item, ruleObject) {
      ruleObject.type = 'input';
      ruleObject.validate = [];
      ruleObject.props = {
        placeholder: '请输入' + item.displayName
      };

      if (item.displayRule.isRequired === 1) {
        ruleObject.validate.push({
          type: 'string',
          required: true,
          message: '请输入' + item.displayName
        });
      }

      ruleObject.validate = ruleObject.validate.concat(this.buildLengthValidationRules(item));
      return ruleObject;
    },

    buildSelectSingleRule(item, ruleObject) {
      ruleObject.type = 'select';
      ruleObject.validate = [];
      ruleObject.props = {
        multiple: false,
        placeholder: '请选择' + item.displayName
      };
      ruleObject.options = this.parseSelectOptions(item.displayRule.selectOptions);

      if (item.displayRule.isRequired === 1) {
        ruleObject.validate.push({
          type: 'string',
          required: true,
          message: '请选择' + item.displayName
        });
      }
      return ruleObject;
    },

    buildSelectMultipleRule(item, ruleObject) {
      ruleObject.type = 'select';
      ruleObject.validate = [];
      ruleObject.props = {
        multiple: true
      };
      ruleObject.value = [];
      ruleObject.options = this.parseSelectOptions(item.displayRule.selectOptions);
      return ruleObject;
    },

    buildUploadPicRule(title, fieldName, fieldPreviewIndex) {
      let ruleObject = {
        col: { span: 24 },
        title: title,
        type: 'upload',
        field: fieldName
      };

      ruleObject.value = [];
      ruleObject.props = {
        type: 'select',
        uploadType: 'image',
        showFileList: true,
        multiple: false,
        name: 'uploadFile',
        listType: 'picture-card',
        headers: this.getUploadHeaders,
        action: window.config.baseUrl + 'admin/app/dc/upload',
        data: {
          asImage: true
        },
        limit: 1,
        onSuccess: (response, file, fileList) => {
          this.onUploadImageSuccess(response, file, fileList, fieldName, fieldPreviewIndex);
        },
        onPreview: file => {
          this.onPreviewImage(file);
        },
        // onRemove: this.onRemoveFile,
        onExceed: this.onExceedFile,
        // eslint-disable-next-line no-useless-escape
        accept: 'image/*',
        fileList: this.formData[fieldName]
      };
      return ruleObject;
    },

    // buildUploadFileRule(item, ruleObject) {
    //   ruleObject.type = 'upload';
    //   ruleObject.value = [];
    //   ruleObject.props = {
    //     type: 'select',
    //     uploadType: 'file',
    //     showFileList: true,
    //     multiple: true,
    //     name: 'uploadFile',
    //     listType: 'text',
    //     headers: this.getUploadHeaders,
    //     action: this.getActionUrl,
    //     onSuccess: this.customSuccess('file'),
    //     onPreview: this.handlePreview,
    //     onRemove: this.onRemoveFile,
    //     onExceed: this.onExceedFile,
    //     data: this.getUploadData(item.name, false),
    //     // eslint-disable-next-line no-useless-escape
    //     accept: 'file/*',
    //     fileList: []
    //   };
    //
    //   if (
    //     item.displayRule.uploadMaxNumber !== undefined &&
    //     item.displayRule.uploadMaxNumber !== '' &&
    //     item.displayRule.uploadMaxNumber !== null
    //   ) {
    //     ruleObject.props.limit = Number(item.displayRule.uploadMaxNumber);
    //   }
    //
    //   if (
    //     item.displayRule.uploadMaxSize !== undefined &&
    //     item.displayRule.uploadMaxSize !== '' &&
    //     item.displayRule.uploadMaxSize !== null
    //   ) {
    //     ruleObject.props.beforeUpload = this.createBeforeUpload(item.displayRule.uploadMaxSize);
    //   }
    //   return ruleObject;
    // },

    buildCascaderRule(item, ruleObject) {
      ruleObject.type = 'cascader';
      ruleObject.value = [];
      ruleObject.props = {
        clearable: true,
        placeholder: '请选择' + item.displayName,
        options: []
      };

      if (
        item.displayRule.cascaderOptions !== '' &&
        item.displayRule.cascaderOptions !== null &&
        item.displayRule.cascaderOptions !== undefined
      ) {
        ruleObject.props.options = this.parseCategories(item.displayRule.cascaderOptions);
      }
      return ruleObject;
    },

    buildDatePickerRule(item, ruleObject) {
      ruleObject.type = 'DatePicker';
      ruleObject.value = '';
      ruleObject.props = {
        type: 'date',
        format: 'yyyy-MM-dd'
      };
      return ruleObject;
    },

    buildValidationRules(item) {
      let validate = [];
      if (item.displayRule.isRequired === 1) {
        validate.push({
          type: 'string',
          required: true,
          message: '请输入' + item.displayName,
          trigger: 'blur'
        });
      }
      return validate.concat(this.buildLengthValidationRules(item));
    },

    buildLengthValidationRules(item) {
      let validate = [];
      if (item.displayRule.validateRule && item.displayRule.validateRule.length > 0) {
        item.displayRule.validateRule.forEach(rule => {
          if (rule === 'maxLength') {
            validate.push({
              max: Number(item.displayRule.validateMaxLength),
              message: '长度不能超过' + item.displayRule.validateMaxLength
            });
          } else if (rule === 'minLength') {
            validate.push({
              min: Number(item.displayRule.validateMinLength),
              message: '长度不能小于' + item.displayRule.validateMinLength
            });
          }
        });
      }
      return validate;
    },

    parseSelectOptions(selectOptions) {
      if (!selectOptions) return [];
      console.log('this.selectOptions', selectOptions);
      console.log('this.getPmDict', this.getPmDict);
      let options = this.getPmDict[selectOptions];
      if (!options) return [];
      console.log('options', options);
      return options.map(item => {
        return {
          value: item.id,
          label: item.name,
          disabled: false
        };
      });
    },

    // 对cascader的options进行处理
    parseCategories(text) {
      const lines = text.split('\n').filter(line => line.trim() !== ''); // 按行分割并移除空行
      const result = []; // 存储最终结果的数组
      const map = {}; // 用于快速查找父节点的映射

      // 解析每一行并构建映射和树结构
      for (const line of lines) {
        const [value, label, parentId] = line.split(':::').map(s => s.trim());

        // 创建当前节点对象
        const node = {
          value,
          label
        };

        // 如果当前节点有父节点，将其添加到父节点的 children 中
        if (parentId && map[parentId]) {
          map[parentId].children = map[parentId].children || [];
          map[parentId].children.push(node);
        } else {
          // 如果没有父节点，则添加到最终结果数组中
          result.push(node);
        }

        // 将当前节点添加到映射中以便后续查找
        map[value] = node;
      }

      return result;
    },
    onExceedFile() {
      this.$message.warning('选择上传的文件数，超过了允许继续上传的数量！');
    },
    onPreviewImage(file, a, b) {
      this.imagePreview.show = true;
      for (let i = 0; i < this.imagePreview.imageList.length; i++) {
        if (this.imagePreview.imageList[i] === file.url) {
          this.imagePreview.index = i;
          break;
        }
      }
    },
    onUploadImageSuccess(response, file, fileList, fieldName, fieldPreviewIndex) {
      file.url =
        window.config.baseUrl +
        response.data.downloadUri.slice(1) +
        '?asImage=true&filename=' +
        response.data.filename;
      console.log('onUploadImageSuccess', file);
      console.log('onUploadImageSuccess', fileList);
      this.$nextTick(() => {
        let previewImages = [];
        this.formData.farImage && previewImages.push(this.formData.farImage);
        this.formData.nearImage && previewImages.push(this.formData.nearImage);
        this.formData.innerImage && previewImages.push(this.formData.innerImage);
        this.imagePreview.imageList = [...previewImages];
        console.log('onUploadImageSuccess', previewImages);
      });
      console.log('onUploadImageSuccess', this.formData[fieldName]);
    },
    // 文件上传成功的函数
    // 照片的预览函数
    loadData(reload = false) {
      PiplineProjectController.viewLayerData(this, {
        projectId: this.projectId,
        layerId: this.layerId,
        dataId: this.dataId,
        isEditData: true
      }).then(res => {
        let resData = res.data;
        let images = [];
        // 处理远景、近景、井内照片
        if (resData && resData.image1) {
          resData.farImage = [window.config.baseUrl + resData.image1.slice(1)];
          images.push(resData.farImage);
        }
        if (resData && resData.image2) {
          resData.nearImage = [window.config.baseUrl + resData.image2.slice(1)];
          images.push(resData.nearImage);
        }
        if (resData && resData.image3) {
          resData.innerImage = [window.config.baseUrl + resData.image3.slice(1)];
          images.push(resData.innerImage);
        }

        if (resData && resData.relate_images) {
          resData.nexImage = resData.relate_images.map(item => {
            return window.config.baseUrl + item.slice(1);
          });
        }
        console.log('resData', resData);
        if (resData && images.length > 0) {
          this.imagePreview.imageList = [...images];
        }
        this.formData = resData;
        if (reload) {
          this.fApi.coverValue(res.data);
        }
      });
    }
  },
  mounted() {
    console.log(this.fieldList);
    console.log(this.layerConfig);
    this.getRuleData();
    console.log(this.ruleData);
  },
  watch: {
    // fieldList: {
    //   handler (newVal) {
    //     console.log(newVal)
    //   },
    //   deep: true
    // },
    // editData: {
    //   handler (newVal) {
    //     this.editDcTaskData = null;
    //
    //     this.editDcTaskData = this.getEditData(newVal);
    //
    //     // this.editDcTaskData = this.getEditData();
    //     // this.uploadWidgetImpl = new UploadWidget(this.uploadNumber.picMaxNumber ? this.uploadNumber.picMaxNumber : 0);
    //   },
    //   deep: true
    // }
  },
  computed: {
    getUploadHeaders() {
      let token = getToken();
      let appId = getAppId();
      // let menuIdJsonStr = window.sessionStorage.getItem('currentMenuId');
      // let currentMenuId;
      // if (menuIdJsonStr != null) {
      //   currentMenuId = (JSON.parse(menuIdJsonStr) || {}).data;
      // }
      let header = {
        Authorization: token
        // MenuId: currentMenuId
      };
      if (appId != null && appId !== '') header.AppCode = appId;

      return header;
    },
    ...mapGetters(['getPmDict'])
  }
};
</script>

<style scoped>
.toolbar {
  width: 100%;
  text-align: right;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 72px;
  height: 72px;
  margin: 0 4px 4px 0;
}
::v-deep ._fc-upload > div:first-child {
  /* 第一个子元素是 div 时应用 */
  display: flex !important;
}

::v-deep .el-upload--picture-card {
  width: 72px;
  height: 72px;
  line-height: 96px;
}

::v-deep .fc-upload-btn {
  width: 36px;
  height: 36px;
  line-height: 48px;
}

::v-deep .overlength-label {
  position: relative;
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
::v-deep .overlength-label:hover {
  overflow: visible;
}
::v-deep .overlength-label:hover::after {
  content: var(--full-text);
  position: absolute;
  bottom: 2rem;
  left: 0;
  background: #000;
  color: #fff;
  padding: 4px 8px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 9999;
  border-radius: 3px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  pointer-events: none;
  max-width: 400px;
  overflow: visible;
  text-overflow: ellipsis;
  z-index: 9999;
}

::v-deep .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before,
.el-form-item.is-required:not(.is-no-asterisk)
  .el-form-item__label-wrap
  > .el-form-item__label:before {
  position: absolute;
  left: -10px;
}
</style>
